﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using CrystalDecisions.CrystalReports.Engine;

namespace 提交管理平台V1
{
    public partial class OtherInfoFrm : Form
    {
        ReportDataSet Rds;
        string ContractNo;
        DataTable dt;
        DataTable dtPrinterSettings;
        string tmpMemo;

        public OtherInfoFrm(string 购货单位,string 生产单位,string 制票人,string 附件备注,DataTable tmpdt)
        {
            InitializeComponent();
            textBox1.Text = 购货单位;
            textBox2.Text = 生产单位;
            textBox3.Text = 制票人;
            textBox4.Text = 附件备注;
            Rds = new ReportDataSet();
            dt = tmpdt;
        }

        private void iniPrinterSettings()
        {
            if (dtPrinterSettings == null)
            {
                dtPrinterSettings = new DataTable();
                dtPrinterSettings.Columns.Add("模板");
                dtPrinterSettings.Columns.Add("指定打印机");
            }
            else
            {
                dtPrinterSettings.Rows.Clear();
            }
            if (Properties.Settings.Default.PrinterSettings.Length > 0)
            {
                string[] tmpSettings = Properties.Settings.Default.PrinterSettings.Split(';');
                if (tmpSettings.Length % 2 != 0)
                {
                    MessageBox.Show("打印机设置有误，请检查后重新设置！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    this.Close();
                }
                DataRow r;
                for (int i = 0; i < tmpSettings.Length - 1; i += 2)
                {
                    r = dtPrinterSettings.NewRow();
                    r["模板"] = tmpSettings[i];
                    r["指定打印机"] = tmpSettings[i + 1];
                    dtPrinterSettings.Rows.Add(r);
                }
            }
        }

        private int GetSettingIndex(string strTempletName)
        {
            int ret = -1;
            for (int i = 0; i < dtPrinterSettings.Rows.Count; i++)
            {
                if (dtPrinterSettings.Rows[i]["模板"].ToString() == strTempletName)
                {
                    ret = i;
                    break;
                }
            }
            return ret;
        }

        private void iniReportData(DataTable tmpdt)
        {
            try
            {
                DataRow r;
                Rds.Tables["ReportData"].Rows.Clear();
                DataView dv = tmpdt.DefaultView;
                dv.Sort = "型号,尺寸,特性,电压,容量";
                tmpdt = dv.ToTable();
                ContractNo = tmpdt.Rows[0]["合同号"].ToString().Trim ();
                int count = 1;
                string tmpModel = "";
                for (int i = 0; i < tmpdt.Rows.Count; i++)
                {
                    r = Rds.Tables["ReportData"].NewRow();
                    r["序号"] = tmpdt.Rows[i]["序号"];
                    if (tmpdt.Rows[i]["型号"].ToString().ToUpper() != tmpModel)
                    {
                        r["合同号"] = tmpdt.Rows[i]["合同号"];
                        tmpModel = tmpdt.Rows[i]["型号"].ToString().ToUpper();
                        count = 1;
                    }
                    else
                    {
                        r["合同号"] = " ";
                        count++;
                    }
                    if (count > 6)
                    {
                        count = 1;
                        r["合同号"] = tmpdt.Rows[i]["合同号"];
                    }
                    if (tmpdt.Rows[i]["合同号"].ToString().Trim () != ContractNo)
                    {
                        MessageBox.Show("选择了多个合同号的产品，每次只能处理一个合同号！", "错误");
                        i = tmpdt.Rows.Count;
                        this.Close();
                        return;
                    }
                    if (tmpdt.Rows[i]["订单编号"] != null && tmpdt.Rows[i]["订单编号"].ToString().Length == 12 && tmpdt.Rows[i]["订单项次"].ToString()!="")
                    {
                        r["订单项次"] = tmpdt.Rows[i]["订单编号"].ToString().Substring(tmpdt.Rows[i]["订单编号"].ToString().Length - 3) + "-" + tmpdt.Rows[i]["订单项次"];
                    }
                    else
                    {
                        r["订单项次"] = "";
                    }
                    r["单价"] = tmpdt.Rows[i]["单价"];
                    r["数量"] = tmpdt.Rows[i]["提交数量"];
                    string strTmpModel = string.Empty;
                    if (comboBox1.Text == "发票附件")
                    {
                        r["备注"] = tmpdt .Rows [i]["用户计划号"];
                        if (GeneralTools.GetString(tmpdt.Rows[i]["引出端形式"], string.Empty).Equals(string.Empty))
                        {
                            r["型号规格"] = tmpdt.Rows[i]["型号"].ToString() + "-" + tmpdt.Rows[i]["尺寸"].ToString() + "-" + tmpdt.Rows[i]["特性"].ToString() + "-" + tmpdt.Rows[i]["电压"].ToString() + "-" + tmpdt.Rows[i]["容量"].ToString() + "(" + tmpdt.Rows[i]["批号"].ToString() + ")";
                        }
                        else
                        {
                            r["型号规格"] = tmpdt.Rows[i]["型号"].ToString() + "-" + tmpdt.Rows[i]["尺寸"].ToString() + "-" + tmpdt.Rows[i]["特性"].ToString() + "-" + tmpdt.Rows[i]["电压"].ToString() + "-" + tmpdt.Rows[i]["容量"].ToString() + "-" + tmpdt.Rows[i]["引出端形式"].ToString() + "(" + tmpdt.Rows[i]["批号"].ToString() + ")";
                        }
                        strTmpModel = GeneralTools.GetString(r["型号规格"], string.Empty);
                        while (strTmpModel.Contains("--"))
                        {
                            strTmpModel = strTmpModel.Replace("--", "-");
                        }
                        if(textBox2.Text !="微波事业部")
                        {
                            if (strTmpModel.Contains("-("))
                            {
                                strTmpModel = strTmpModel.Replace("-(", "-");
                            }
                        }
                        r["型号规格"] = strTmpModel;
                    }
                    if (comboBox1.Text == "缴库单" || comboBox1.Text == "外标签")
                    {
                        r["备注"] = tmpdt.Rows[i]["批号"].ToString();
                        if (GeneralTools.GetString(tmpdt.Rows[i]["引出端形式"], string.Empty).Equals(string.Empty))
                        {
                            r["型号规格"] = tmpdt.Rows[i]["型号"].ToString() + "-" + tmpdt.Rows[i]["尺寸"].ToString() + "-" + tmpdt.Rows[i]["特性"].ToString() + "-" + tmpdt.Rows[i]["电压"].ToString() + "-" + tmpdt.Rows[i]["容量"].ToString();
                        }
                        else
                        {
                            r["型号规格"] = tmpdt.Rows[i]["型号"].ToString() + "-" + tmpdt.Rows[i]["尺寸"].ToString() + "-" + tmpdt.Rows[i]["特性"].ToString() + "-" + tmpdt.Rows[i]["电压"].ToString() + "-" + tmpdt.Rows[i]["容量"].ToString() + "-" + tmpdt.Rows[i]["引出端形式"].ToString();
                        }
                        strTmpModel = GeneralTools.GetString(r["型号规格"], string.Empty);
                        while (strTmpModel.EndsWith("-"))
                        {
                            strTmpModel = strTmpModel.Substring(0, strTmpModel.Length - 1);
                        }
                        r["型号规格"] = strTmpModel;
                    }
                    if (comboBox1.Text == "DPA抽样费")
                    {
                        r["备注"] = tmpdt.Rows[i]["用户计划号"];
                        r["数量"] = tmpdt.Rows[i]["DPA数量"];
                        if (GeneralTools.GetString(tmpdt.Rows[i]["引出端形式"], string.Empty).Equals(string.Empty))
                        {
                            r["型号规格"] = tmpdt.Rows[i]["型号"].ToString() + "-" + tmpdt.Rows[i]["尺寸"].ToString() + "-" + tmpdt.Rows[i]["特性"].ToString() + "-" + tmpdt.Rows[i]["电压"].ToString() + "-" + tmpdt.Rows[i]["容量"].ToString() + "(" + tmpdt.Rows[i]["批号"].ToString() + ")";
                        }
                        else
                        {
                            r["型号规格"] = tmpdt.Rows[i]["型号"].ToString() + "-" + tmpdt.Rows[i]["尺寸"].ToString() + "-" + tmpdt.Rows[i]["特性"].ToString() + "-" + tmpdt.Rows[i]["电压"].ToString() + "-" + tmpdt.Rows[i]["容量"].ToString() + "-" + tmpdt.Rows[i]["引出端形式"].ToString() + "(" + tmpdt.Rows[i]["批号"].ToString() + ")";
                        }
                    }
                    if (comboBox1.Text == "DPA缴库单")
                    {
                        r["数量"] = tmpdt.Rows[i]["DPA数量"];
                        r["备注"] = tmpdt.Rows[i]["批号"].ToString();
                        if (GeneralTools.GetString(tmpdt.Rows[i]["引出端形式"], string.Empty).Equals(string.Empty))
                        {
                            r["型号规格"] = tmpdt.Rows[i]["型号"].ToString() + "-" + tmpdt.Rows[i]["尺寸"].ToString() + "-" + tmpdt.Rows[i]["特性"].ToString() + "-" + tmpdt.Rows[i]["电压"].ToString() + "-" + tmpdt.Rows[i]["容量"].ToString();
                        }
                        else
                        {
                            r["型号规格"] = tmpdt.Rows[i]["型号"].ToString() + "-" + tmpdt.Rows[i]["尺寸"].ToString() + "-" + tmpdt.Rows[i]["特性"].ToString() + "-" + tmpdt.Rows[i]["电压"].ToString() + "-" + tmpdt.Rows[i]["容量"].ToString() + "-" + tmpdt.Rows[i]["引出端形式"].ToString();
                        }
                    }
                    Rds.Tables["ReportData"].Rows.Add(r);
                }
                dataGridView1.DataSource = Rds.Tables["ReportData"];
                dataGridView1.Columns["序号"].Visible = false;
                RemoveContractNo();
                if (comboBox1.Text == "外标签")
                {
                    FillContractNo();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void FillContractNo()
        {
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                dataGridView1.Rows[i].Cells["合同号"].Value = dataGridView1.Rows[0].Cells["合同号"].Value;
            }
        }

        private void RemoveContractNo()
        {
            if (dataGridView1.Rows.Count > 0)
            {
                int Count = 1;
                dataGridView1.Rows[0].Cells["合同号"].Value = ContractNo;
                for (int i = 1; i <dataGridView1.Rows.Count; i++)
                {
                    Count++;
                    if (i > 0)
                    {
                        if (dataGridView1.Rows[i].Cells["型号规格"].Value.ToString().Substring(0, 5) == dataGridView1.Rows[i-1].Cells["型号规格"].Value.ToString().Substring(0, 5))
                        {
                            if (Count != 1)
                            {
                                dataGridView1 .Rows [i].Cells["合同号"].Value  = "";
                            }
                            else
                            {
                                dataGridView1.Rows[i].Cells["合同号"].Value = ContractNo;
                            }
                        }
                        else
                        {
                            dataGridView1.Rows[i].Cells["合同号"].Value = ContractNo;
                            Count = 1;
                        }
                    }
                    if (Count == 6)
                    {
                        Count = 0;
                    }
                }
            }
        }

        private void OtherInfoFrm_Load(object sender, EventArgs e)
        {
            comboBox1.Items.Clear();
            comboBox1.Items.Add("发票附件");
            comboBox1.Items.Add("缴库单");
            comboBox1.Items.Add("DPA抽样费");
            comboBox1.Items.Add("外标签");
            comboBox1.Items.Add("DPA缴库单");
            comboBox1.SelectedIndex = 0;
            dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            iniPrinterSettings();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Rds.Tables["OtherInfo"].Rows.Clear();
            DataRow r = Rds.Tables["OtherInfo"].NewRow();
            r["购货单位"] = textBox1.Text.Trim();
            r["生产单位"] = textBox2.Text.Trim();
            r["制票人"] = textBox3.Text.Trim();
            r["附件备注"] = textBox4.Text.Trim();
            r["发票号"] = textBox5.Text.Trim();
            Rds.Tables["OtherInfo"].Rows.Add(r);
            reportpreviewFrm newreportpreviewFrm = new reportpreviewFrm((DataSet)Rds, GetReportFileName());
            newreportpreviewFrm.ShowDialog();
            //InvokePreviewFrm newinvokepreviewFrm = new InvokePreviewFrm(Rds,GetReportFileName () );
            //newinvokepreviewFrm.ShowDialog();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            int nCopies;
            try 
            {
                nCopies =int.Parse (textBox6 .Text );
            }
            catch 
            {
                MessageBox .Show ("打印份数输入错误，打印终止！");
                textBox6 .Focus ();
                return ;
            }
            Rds.Tables["OtherInfo"].Rows.Clear();
            DataRow r = Rds.Tables["OtherInfo"].NewRow();
            r["购货单位"] = textBox1.Text.Trim();
            r["生产单位"] = textBox2.Text.Trim();
            r["制票人"] = textBox3.Text.Trim();
            r["附件备注"] = textBox4.Text.Trim();
            r["发票号"] = textBox5.Text.Trim();
            Rds.Tables["OtherInfo"].Rows.Add(r);
            CrystalDecisions.CrystalReports.Engine.ReportDocument Rdoc = new CrystalDecisions.CrystalReports.Engine.ReportDocument();
            FileInfo fi = new FileInfo(GetReportFileName());
            Rdoc.Load(fi.FullName);
            int ind = GetSettingIndex(fi.Name.Substring(0, fi.Name.Length - 4));
            if (ind != -1)
            {
                Rdoc.PrintOptions.PrinterName = dtPrinterSettings.Rows[ind]["指定打印机"].ToString();
            }
            Rdoc.SetDataSource(Rds);
            //int iTotalPageCount=Rdoc.FormatEngine.GetLastPageNumber(new ReportPageRequestContext());
            //Rdoc.Refresh();
            while (!Rdoc.IsLoaded)
            { }
            try
            {
                Rdoc.PrintToPrinter(nCopies, false, 0, 0);
                SqlTools sqt = new SqlTools(GeneralTools.GetConnectionString("192.168.1.1", "DefualtDataBase"));
                //SqlTools sqt = new SqlTools(GeneralTools.GetConnectionString(".", "DefualtDataBase"));
                string strTmpUpdateString = "update qzkfc set 已开票='已开票',开票日期=GetDate() where 序号=@序号";
                for (int i = 0; i < Rds.Tables["ReportData"].Rows.Count; i++)
                {
                    sqt.DoCmdExecuteNonQuery(strTmpUpdateString.Replace("@序号", GeneralTools.GetString(Rds.Tables["ReportData"].Rows[i]["序号"], string.Empty)));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private string GetReportFileName()
        {
            string Path = Application.StartupPath;
            if (Path[Path.Length - 1] != '\\')
            {
                Path += "\\";
            }
            string tmpReportFileName = Path + "Template\\开票_" + comboBox1.Text + ".rpt"; 
            if(textBox2.Text =="微波事业部"&&comboBox1.Text =="发票附件")
            {
                tmpReportFileName = Path + "Template\\开票_" + comboBox1.Text + "_微波.rpt";
            }
            return (tmpReportFileName);
        }

        private void dataGridView1_DragDrop(object sender, DragEventArgs e)
        {
            int Index = GetRowFromPoint(e.X, e.Y);

            if (Index > -1)
            {
                if (e.Data.GetDataPresent(typeof(DataGridViewRow )))
                {
                    DataGridViewRow  r = (DataGridViewRow )e.Data.GetData(typeof(DataGridViewRow ));
                    DataTable tmpdt = (DataTable)dataGridView1.DataSource;
                    DataRow r1 = tmpdt.NewRow ();
                    for (int i = 0; i < tmpdt.Columns.Count; i++)
                    {
                        r1[i] = r.Cells[i].Value;
                    }
                    tmpdt.Rows.RemoveAt(r.Index );
                    tmpdt.Rows.InsertAt(r1, Index);
                    dataGridView1.CurrentCell = dataGridView1.Rows[Index].Cells[0];
                    RemoveContractNo();
                }
            }
        }

        private int GetRowFromPoint(int x, int y)
        {
            for (int i = 0; i < dataGridView1.RowCount; i++)
            {
                Rectangle rec = dataGridView1.GetRowDisplayRectangle(i, false);

                if (dataGridView1.RectangleToScreen(rec).Contains(x, y))
                    return i;
            }
            return -1;
        }

        private void dataGridView1_CellMouseMove(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left && e.Clicks < 2)
            {
                if (e.ColumnIndex == -1 && e.RowIndex > -1)
                {
                    //DataTable tmpdt=(DataTable )dataGridView1.DataSource ;
                    dataGridView1.DoDragDrop(dataGridView1.Rows [e.RowIndex ], DragDropEffects.Move);
                }
            }
        }

        private void dataGridView1_DragEnter(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.Move;
        }

        private void 删除选定行ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count > 0)
            {
                for (int i = dataGridView1.Rows.Count-1 ; i >=0; i--)
                {
                    if (dataGridView1.Rows[i].Selected)
                    {
                        dataGridView1.Rows.Remove(dataGridView1.Rows[i]);
                    }
                }
                RemoveContractNo();
            }
        }

        private void dataGridView1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Clicks < 2 && e.Button == MouseButtons.Right)
            {
                DataGridView.HitTestInfo hi = dataGridView1.HitTest(e.X, e.Y);
                if (hi.Type == DataGridViewHitTestType.Cell && dataGridView1.Rows[hi.RowIndex ].Selected)
                {
                    contextMenuStrip1.Show(dataGridView1, e.Location);
                }
            }
        }

        private void 汇总选定行ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string Model;
            int Count=0;
            int tmpnum;
            if (dataGridView1.SelectedRows.Count > 1)
            {
                Model = dataGridView1.SelectedRows[0].Cells["型号规格"].Value.ToString();
                for (int i = 0; i < dataGridView1.SelectedRows.Count; i++)
                {
                    if (dataGridView1.SelectedRows[i].Cells["型号规格"].Value.ToString() == Model)
                    {
                        try
                        {
                            tmpnum = int.Parse(dataGridView1.SelectedRows[i].Cells["数量"].Value.ToString());
                        }
                        catch
                        {
                            tmpnum = 0;
                        }
                        Count += tmpnum;
                    }
                    else
                    {
                        MessageBox.Show("不同的型号规格不能汇总！");
                        return;
                    }
                }
                while (dataGridView1.SelectedRows.Count > 1)
                {
                    dataGridView1.Rows.Remove((DataGridViewRow)dataGridView1.SelectedRows[0]);
                }
                dataGridView1.SelectedRows[0].Cells["数量"].Value = Count;
                RemoveContractNo();
            }
            else
            {
                MessageBox.Show("选择一条以上的记录才能进行汇总！");
                return;
            }
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBox1.Text == "DPA抽样费" || comboBox1.Text == "DPA缴库单")
            {
                tmpMemo = textBox4.Text;
                textBox4.Text = "DPA抽样费";
            }
            else
            {
                if (tmpMemo != null)
                {
                    textBox4.Text = tmpMemo;
                }
            }
            iniReportData(dt);
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            PrinterSettingsFrm newPrinterSettingsFrm = new PrinterSettingsFrm();
            newPrinterSettingsFrm.ShowDialog();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (textBox7.Text.Trim().Length > 0)
            {
                    ContractNo =textBox7 .Text .Trim ();
                    RemoveContractNo();
            }
            else
            {
                textBox7.SelectAll();
                textBox7.Focus();
            }
        }
    }
}